<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>  
<%@ page import="java.util.*"%>
<%@ page import="com.shopcart.controller.*"%>
<%@ page import="com.shopcart.entity.*"%>

<%
	List<Product> products = ((ItemController) session.getAttribute("itemController")).getProducts();
	request.setAttribute("products", products);
%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet"
	media="screen" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>

<style type="text/css">
.table-nonfluid {
	width: auto;
}
</style>

<title>BOUN SHOP</title>
</head>
<body>
	<div class="navbar navbar-inverse">
		<div class="navbar-inner">
			<a class="brand" href="home.jsp">BOUN SHOP</a>
			<ul class="nav">
				<li><a href="home.jsp">Home</a></li>
				<!-- 
				 -->
				<li class="active"><a href="cart.jsp">My Cart</a></li>
				<li><a href="history.jsp">My History</a></li>
			</ul>
			<ul class="nav pull-right">
				<li><button type="button" class="btn btn-success" id="checkout">Checkout</button></li>
				<li class="divider-vertical"></li>
				<li><button type="button" class="btn btn-danger"
						onclick="logout();">Log Out</button></li>
			</ul>
		</div>
	</div>

	<div class="container-fluid">
		<div class="row-fluid">

			<div class="span6">
				<center>
					<h2>Shop</h2>
					<table class="table table-striped table-nonfluid"
						style="min-width: 50%">
						<thead>
							<tr>
								<th>Match</th>
								<th>Name</th>
								<th>Quantity</th>
								<th></th>
							</tr>
						</thead>
						<tbody>
							<c:forEach var="p" items="${products}">
								<tr>
									<c:set var="contains" value="false"/>
									<c:set var="hasMatching" value="false"/>
									<td>
										<c:forEach var="item" items="${cartController.cart.items}">
											<c:if test = "${p.id == item.product.id}">
												<c:set var="contains" value="true"/>
											</c:if>
											<c:forEach var="matchItem" items="${item.product.matchingProducts}">
												<c:if test = "${p.id == matchItem.id}">
													<c:set var="hasMatching" value="true"/>
												</c:if>
											</c:forEach>
										</c:forEach>
										<c:if test = "${!contains && hasMatching}">
											<i class="icon-ok"></i>
										</c:if>
									</td>
									<td>${p.name}</td>
									<td>${p.quantity}</td>
									<td>
										<div class="btn-group pull-right">
											<c:if test = "${p.quantity != 0}">
												<c:if test = "${contains == true}">
													<button data-name="${p.name}" data-id="${p.id}" data-max="${p.quantity}"
														type="button" class="btn addToCartButton" disabled="disabled">Add</button>
												</c:if>
												
												<c:if test = "${contains == false}">
													<button data-name="${p.name}" data-id="${p.id}" data-max="${p.quantity}"
														type="button" class="btn addToCartButton">Add</button>
												</c:if>
											</c:if>
											<c:if test = "${p.quantity == 0}">
												<c:if test = "${contains == true}">
													<button data-name="${p.name}" data-id="${p.id}" data-max="${p.quantity}"
														type="button" class="btn addToCartButton" disabled="disabled">Add</button>
												</c:if>
												
												<c:if test = "${contains == false}">
													<button data-id="${p.id}"
													type="button" class="btn warnLater">Warn Me Later</button>
												</c:if>
											</c:if>
										</div>
									</td>
								</tr>
							</c:forEach>
						</tbody>
					</table>
				</center>

			</div>
			<div class="span6">
				<center>

					<h2>Basket</h2>

					<table class="table table-striped table-nonfluid">
						<thead>
							<tr>
								<th></th>
								<th>Name</th>
								<th>Count</th>
							</tr>
						</thead>
						<tbody id="cart-items">
							<c:forEach var="item" items="${cartController.cart.items}">
								<tr>
									<td><button type="button" data-id="${item.product.id}" class="close itemDelete">×</button></td>
									<td><input type="hidden" name="productId" value="${item.product.id}" />${item.product.name}</td>
									<td>
										<div class="input-append">
										<input class="span4" productId="${item.product.id}" type="text" name="itemCount${item.product.id}" value="${item.count}">
										<span class="add-on"><a class="minus"><i class="icon-minus-sign"></i></a></span>
										<span class="add-on"><a class="plus" data-id="${item.product.id}" max="${item.product.quantity + item.count}"><i class="icon-plus-sign"></i></a></span></div>
									</td>
								</tr>
							</c:forEach>
						</tbody>
					</table>
					<button class="btn btn-primary updateCartButton">Update Items</button>
				</center>
			</div>
		</div>
	</div>
	
	<script type="text/javascript">
		(function() {
			var cart_items = $('#cart-items');

			function addToCart(id, productName, max) {
				var closeBut = '<td><button type="button" data-id="'+id+'" class="close itemDelete">×</button></td>';
				var hidden = '<input type="hidden" name="productId" value="'+id+'" />';
				var title = '<td>' + hidden + productName + '</td>';
				var no = '<td><div class="input-append">'
						+ '<input class="span4" productId="' + id + '" type="text" name="itemCount' + id + '" value="1">'
						+ '<span class="add-on"><a class="minus"><i class="icon-minus-sign"></i></a></span>'
						+ '<span class="add-on"><a class="plus" max="' + max + '"><i class="icon-plus-sign"></i></a></span></div></td>';
				cart_items.append($("<tr>" + closeBut + title + no + "</tr>"));
			}

			$('div.container-fluid').on('click', 'button.addToCartButton',
					function() {
						$this = $(this);
						addToCart($this.data('id'), $this.data('name'), $this.data('max'));
						$this.attr('disabled', 'disabled');
					});
			$('div.container-fluid').on('click', 'a.minus',
					function() {
						$this = $(this);
						var countIn = $this.parent().siblings().first();
						if(countIn.val() != 1)
							countIn.val(parseInt(countIn.val()) - 1);
					});
			$('div.container-fluid').on('click', 'a.plus',
					function() {
						$this = $(this);
						var countIn = $this.parent().siblings().first();
						
						if (parseInt(countIn.val()) < parseInt($this.attr("max"))) {
							countIn.val(parseInt(countIn.val()) + 1);
						}
					});
			$('div.container-fluid').on('click', 'button.itemDelete',
					function() {
						$this = $(this);
						$this.parent().parent().remove();
						$('button.addToCartButton[data-id=' + $this.data('id') + ']').removeAttr('disabled');
						
					});
			$('.updateCartButton').on('click', function() {
				idList = new Array();
				countList = new Array();
				var myError = false;
				
				$(".span4").each(function() {
					var countValue = $(this).val();
					var itemId = $(this).attr("productId");
					var maxCount = $('a.plus[data-id='+itemId+']').data('max'); 
					if(!countValue.match(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/) || parseInt(countValue) <= 0 ){
						alert('Invalid input: '+countValue);
						myError = true;
						return;
					} 
					else if (parseInt(countValue) > maxCount){
						alert(countValue + ' exceeds maximumn ' + $('button.addToCartButton[data-id='+itemId+']').data('name') + ' value !');
						myError = true;
						return;
					}
					idList.push(itemId);
					countList.push(countValue);
				});
				
				if(myError)
					return;
				
				$.ajax({
					url : "/ShoppingCartWeb/CartServlet?updateCart",
					type : "POST",
					data : {idList : idList, countList : countList},
					success : function(data) {
						location.reload();
					},
					error : function(data) {
						alert('error updating cart');
					}
				});
			});
		})();
		
		$(".warnLater").click(function() {
			$.ajax({
				url : "/ShoppingCartWeb/ItemWarnServlet",
				type : "POST",
				data : {id : $(this).data('id')},
				success : function(data) {
					location.reload();
				},
				error : function(data) {
					alert('error adding product to warn list');
				}
			});
		});
		
		function logout() {
			var form = document.createElement('form');
			form.setAttribute('method', 'post');
			form.setAttribute('action', 'logout');
			form.style.display = 'hidden';
			document.body.appendChild(form);
			form.submit();
		}
		
		$("#checkout").click(function() {
			idList = new Array();
			countList = new Array();
			
			$(".span4").each(function() {
				idList.push($(this).attr("productId"));
				countList.push($(this).val());
			});
			
			if (idList.length != 0 && countList.length != 0) {
				$.ajax({
					url : "/ShoppingCartWeb/CartServlet?createCart",
					type : "POST",
					data : {idList : idList, countList : countList},
					success : function(data) {
						location.reload();
					},
					error : function(data) {
						alert('error creating cart');
					}
				});
			}
		});
	</script>
</body>
</html>
